﻿// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace svs.Mobile.BeyondMedia.FeedCore.RSS
{
	public static class FeedImageCache
	{
		#region Delegates

		public delegate void NewImageDownloadedDelegate(Feed feed);

		#endregion

		private static Size m_imageSize = new Size(46, 46);

		static FeedImageCache()
		{
			if (!Directory.Exists(Configuration.RssImageCachePath))
				Directory.CreateDirectory(Configuration.RssImageCachePath);
		}

		public static bool HasImageToDownload(Feed feed)
		{
			return !string.IsNullOrEmpty(feed.FeedImageUrl) && !HasCachedImageFor(feed);
		}

		public static void DeleteImageCacheFor(Feed feed)
		{
			if (GetFeedImagePath(feed) != null)
				File.Delete(GetFeedImagePath(feed));
		}

		/// <summary>
		/// Deletes the image cache for all files
		/// </summary>
		/// <returns></returns>
		public static int DeleteImageCacheForAllFeeds()
		{
			string[] files = Directory.GetFiles(Configuration.RssImageCachePath);

			int failedCount = 0;
			foreach (string file in files)
			{
				try
				{
					File.Delete(file);
				}
				catch
				{
					failedCount++;
				}
			}

			return failedCount;
		}

		public static bool HasCachedImageFor(Feed feed)
		{
			if (GetFeedImagePath(feed) != null)
				return File.Exists(GetFeedImagePath(feed));

			return false;
		}

		public static string GetFeedImagePath(Feed feed)
		{
			if (string.IsNullOrEmpty(feed.FeedImageUrl) || feed.FeedUri == null)
				return null;

			try
			{
				return Path.Combine(Configuration.RssImageCachePath,
				                    string.Format("{0}_{1:X}.img",
				                                  feed.FeedUri.Host.Replace('.', '_'),
				                                  feed.FeedUri.GetHashCode()));
			}
			catch (Exception ex)
			{
				CoreHelper.WriteLogEntry(string.Format("Unable to Get Feed Image Path for feed: {0}. (Url: {1}). Reason: {2}",feed.Name, feed.FeedUri, ex.Message));
			}

			return null;
		}

		public static string GetTempFeedImagePath(Feed feed)
		{
			return GetFeedImagePath(feed) + ".temp";
		}

		public static void Initialize(Size imageSize)
		{
			m_imageSize = imageSize;
		}

		#region Private Methods

		public static void FormatImage(Feed feed)
		{
			try
			{
				using (Bitmap output = new Bitmap(m_imageSize.Width, m_imageSize.Height))
				{
					using (Graphics gr = Graphics.FromImage(output))
					{
						gr.Clear(Color.WhiteSmoke);

						using (Bitmap img = new Bitmap(GetTempFeedImagePath(feed)))
						{
							float neww, newh;
							if (img.Width >= img.Height)
							{
								neww = m_imageSize.Width;
								float ratio = (float) img.Width/(float) img.Height;
								newh = neww/ratio;
							}
							else
							{
								newh = m_imageSize.Height;
								float ratio = (float) img.Height/(float) img.Width;
								neww = newh/ratio;
							}

							int newW = (int) Math.Floor(neww);
							int newH = (int) Math.Floor(newh);
							int newY = (m_imageSize.Height/2) - (newH/2);
							int newX = (m_imageSize.Width/2) - (newW/2);

							Rectangle scaledImgRect = new Rectangle(newX, newY, newW, newH);

							gr.DrawImage(img, scaledImgRect, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, new ImageAttributes());
							output.Save(GetFeedImagePath(feed), ImageFormat.Bmp);
						}
					}
				}

				File.Delete(GetTempFeedImagePath(feed));
			}
			catch (Exception e)
			{
				CoreHelper.WriteLogEntry("Unablet to Format image for " + GetTempFeedImagePath(feed) + "! Reason: " + e.Message);
			}
		}

		#endregion
	}
}